//
//  ZKUserAccount.swift
//  Weibo
//
//  Created by 郑克哥哥 on 2017/7/26.
//  Copyright © 2017年 郑克哥哥. All rights reserved.
//

import UIKit

//封装OAuth相关的登录接口

class ZKUserAccount: NSObject {
    
    //单例的全局访问点
    static let sharedViewModel:ZKUserAccount = ZKUserAccount()
    
    private override init() {
        super.init()
        
        //从本地沙盒路径解档用户模型对象
        userAccount = UserAccountModel.loadUserAccount()
    }
    
    //引用模型
    var userAccount:UserAccountModel?
    
    //是否登录标记
    var isLogin: Bool {
        
     return accessToken != nil
        
    }
    
    //获取token
    var accessToken: String?{
        guard let token = userAccount?.access_token else{
            
            return nil
        }
        
        //判断token是否过期
        let result = userAccount?.expiresDate?.compare(Date())
        if result == ComparisonResult.orderedDescending {
            
            //表示没过期
            return token
        }
        return nil
        
        
        
    }
    
    //通过授权码获取令牌(accessToken)
    func requestAccessToken(code:String,callBack:@escaping (Bool)->()) {
        
        NetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            
            if error != nil{
                
                print("error: \(error!)")
                //表示失败
                callBack(false)
                return
            }
            
            let dict = response as! [String:Any]
            //字典转模型
            let userAccount = UserAccountModel(dic: dict)
            
            //获取用户信息
            self.requestUserInfo(userAccount: userAccount,callBack: callBack)
            
            
        }
        
        
    }
    
    //获取用户信息
    private func requestUserInfo(userAccount:UserAccountModel,callBack:@escaping (Bool)->()){
        //令牌
        let token = userAccount.access_token!
        //用户id
        let uid = userAccount.uid
        
        NetworkTools.sharedTools.requestUserInfo(access_token:token , uid: uid) { (response, error) in
            
            if error != nil{
                
                print("error: \(error!)")
                callBack(false)
                return
            }
            
            //转成对应的字典
            let dic = response as! [String:Any]
            //给对象属性赋值
            userAccount.name = dic["name"] as? String
            userAccount.avatar_large = dic["avatar_large"] as? String
            
            print(userAccount.name)
            
            //登录成功
            //保存用户对象
            userAccount.saveUserAccount()
            
            //保存用户模型
            self.userAccount = userAccount
            //登录成功
            callBack(true)
        }
        
        
    }
    
    


}
